<?php
/**
 *友好的时间显示*
$sTime time  时间戳
$type  string (normal,mohu,full)
 */
function friendlyDate($sTime, $type = 'normal', $alt = 'false') {
	if (!$sTime) {
		return '';
	}

	//sTime=源时间，cTime=当前时间，dTime=时间差
	$cTime = time();
	$dTime = $cTime - $sTime;
	$dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
	//$dDay     =   intval($dTime/3600/24);
	$dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
	//normal：n秒前，n分钟前，n小时前，日期
	if ($type == 'normal') {
		if ($dTime < 60) {
			if ($dTime < 10) {
				return '刚刚'; //by yangjs
			} else {
				return intval(floor($dTime / 10) * 10) . "秒前";
			}
		} elseif ($dTime < 3600) {
			return intval($dTime / 60) . "分钟前";
			//今天的数据.年份相同.日期相同.
		} elseif ($dYear == 0 && $dDay == 0) {
			//return intval($dTime/3600)."小时前";
			return '今天' . date('H:i', $sTime);
		} elseif ($dYear == 0) {
			return date("m月d日 H:i", $sTime);
		} else {
			return date("Y-m-d H:i", $sTime);
		}
	} elseif ($type == 'mohu') {
		if ($dTime < 60) {
			return $dTime . "秒前";
		} elseif ($dTime < 3600) {
			return intval($dTime / 60) . "分钟前";
		} elseif ($dTime >= 3600 && $dDay == 0) {
			return intval($dTime / 3600) . "小时前";
		} elseif ($dDay > 0 && $dDay <= 7) {
			return intval($dDay) . "天前";
		} elseif ($dDay > 7 && $dDay <= 30) {
			return intval($dDay / 7) . '周前';
		} elseif ($dDay > 30) {
			return intval($dDay / 30) . '个月前';
		}
		//full: Y-m-d , H:i:s
	} elseif ($type == 'full') {
		return date("Y-m-d , H:i:s", $sTime);
	} elseif ($type == 'ymd') {
		return date("Y-m-d", $sTime);
	} else {
		if ($dTime < 60) {
			return $dTime . "秒前";
		} elseif ($dTime < 3600) {
			return intval($dTime / 60) . "分钟前";
		} elseif ($dTime >= 3600 && $dDay == 0) {
			return intval($dTime / 3600) . "小时前";
		} elseif ($dYear == 0) {
			return date("Y-m-d H:i:s", $sTime);
		} else {
			return date("Y-m-d H:i:s", $sTime);
		}
	}

}
/**
@param $type sqlname(模型表)
@param $int  int  键id
@return id对应模型中的数据
 */
//return 一维数组
function ChangeData($type, $int, $keyid = 'id') {
	for ($k = 0; $k < count($type); $k++) {
		if ($type[$k][$keyid] == $int) {
			return $type[$k];
		}
	}

}
//return 二维数组
function HelpData($type, $int, $keyid = 'id') {
	// return $type;
	for ($k = 0; $k < count($type); $k++) {
		if ($type[$k][$keyid] == $int) {
			$return[] = $type[$k];
		}

	}
	return $return;

}
/*遍历式处理二维数组方法*/
function foreach_child($role, $init, $level = 'level') {
	foreach ($role as $key => $value) {
		if ($role[$key][$level] == $init) {
			$return[] = $role[$key];
		}

	}
	return $return;
}
//查找键值，返回键值对应数据
function foreach_key($role, $init) {
	foreach ($role as $key => $value) {
		if ($key == $init) {
			return $value;
		}

	}
}
/**
根据字段内容。返回要提取的图片地址  @ array
 */
function array_imgurl($dbnews) {
	for ($v = 0; $v < count($dbnews); $v++) {
		foreach ($dbnews[$v] as $key => $value) {
			if ($key == 'image') {
				$img[$key] = $value;
			} else {
				$img[$key] = str_replace('\"', '"', $value);
				$img[$key] = strip_tags($img[$key], '<img><IMG>');
			}
		}
		$img2[] = $img; //接收数组
	}
	//提取出图片路径
	for ($h = 0; $h < count($img2); $h++) {
		foreach ($img2[$h] as $key2 => $value2) {
			preg_match_all('|src="(.*)"|U', $value2, $ret);
			if (!empty($ret['0'])) {
				$inf[] = $ret;
			} else if ($key2 == 'image') {
				$exp[] = explode('|', $value2);
			}
		}
	}
	//提取image图片
	for ($s = 0; $s < count($exp); $s++) {
		for ($d = 0; $d < count($exp[$s]); $d++) {
			//把图片地址组合成一维数组
			$newsimg[] = substr($exp[$s][$d], strrpos($exp[$s][$d], 'Uploads'));
		}
	}
	for ($z = 0; $z < count($inf); $z++) {
		for ($f = 0; $f < count($inf[$z]); $f++) {
			for ($t = 0; $t < count($inf[$z][$f]); $t++) {
				$newsimg[] = substr($inf[$z][$f][$t], strrpos($inf[$z][$f][$t], 'Uploads'));
			}
		}
	}
	//去除特殊符号
	for ($k = 0; $k < count($newsimg); $k++) {
		$newsimg[$k] = str_replace('"', '', $newsimg[$k]);
	}
	//删除重复值 返回剩余数组
	return array_unique($newsimg);
}
// 获取当前页面完整URL地址
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
	return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}
//获取网站主域名
function get_home_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['HTTP_HOST'];
	return $sys_protocal . $php_self;

}
/*
 *获取网站主页绝对地址
 *$y true or false 默认为false 为true不输出后缀'/'
 */
function root($y = false) {
	return $y ? get_home_url() . __ROOT__ : get_home_url() . __ROOT__ . '/';
}
/*提取字符串中的数字*/
function findNum($str = '') {
	$str = trim($str);
	if (empty($str)) {return '';}
	$result = '';
	for ($i = 0; $i < strlen($str); $i++) {
		if (is_numeric($str[$i])) {
			$result .= $str[$i];
		}
	}
	return $result;
}
/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
@param  array  $arr  要连接的数组
@param  string $glue 分割符
@return string
 */
function array_string($arr, $glue = ',') {
	return implode($glue, $arr);
}
/**
 * 把返回的数据集转换成Tree
 * @access public
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
	// 创建Tree
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] = &$list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId = $data[$pid];
			if ($root == $parentId) {
				$tree[] = &$list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent = &$refer[$parentId];
					$parent[$child][] = &$list[$key];
				}
			}
		}
	}
	return $tree;
}
/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) {
	if (is_array($tree)) {
		$refer = array();
		foreach ($tree as $key => $value) {
			$reffer = $value;
			if (isset($reffer[$child])) {
				unset($reffer[$child]);
				tree_to_list($value[$child], $child, $order, $list);
			}
			$list[] = $reffer;
		}
		$list = list_sort_by($list, $order, $sortby = 'asc');
	}
	return $list;
}
/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc') {
	if (is_array($list)) {
		$refer = $resultSet = array();
		foreach ($list as $i => $data) {
			$refer[$i] = &$data[$field];
		}

		switch ($sortby) {
		case 'asc': // 正向排序
			asort($refer);
			break;
		case 'desc': // 逆向排序
			arsort($refer);
			break;
		case 'nat': // 自然排序
			natcasesort($refer);
			break;
		}
		foreach ($refer as $key => $val) {
			$resultSet[] = &$list[$key];
		}

		return $resultSet;
	}
	return false;
}

/**
 * 在数据列表中搜索
 * @access public
 * @param array $list 数据列表
 * @param mixed $condition 查询条件
 * 支持 array('name'=>$value) 或者 name=$value
 * @return array
 */
function list_search($list, $condition) {
	if (is_string($condition)) {
		parse_str($condition, $condition);
	}

	// 返回的结果集合
	$resultSet = array();
	foreach ($list as $key => $data) {
		$find = false;
		foreach ($condition as $field => $value) {
			if (isset($data[$field])) {
				if (0 === strpos($value, '/')) {
					$find = preg_match($value, $data[$field]);
				} elseif ($data[$field] == $value) {
					$find = true;
				}
			}
		}
		if ($find) {
			$resultSet[] = &$list[$key];
		}

	}
	return $resultSet;
}
//效果同上，条件and
function list_and_search($list, $condition) {
	if (is_string($condition)) {
		parse_str($condition, $condition);
	}

	// 返回的结果集合
	$resultSet = array();
	foreach ($list as $key => $data) {
		$find = true; // fixed
		foreach ($condition as $field => $value) {
			if (isset($data[$field])) {
				if (0 === strpos($value, '/')) {
					$find = $find && preg_match($value, $data[$field]); // fixed
				} else {
					$find = $find && $data[$field] == $value; // fixed
				}
			} else {
				$find = false; // fixed
			}
		}
		if ($find) {
			$resultSet[] = &$list[$key];
		}

	}
	return $resultSet;
}
/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) {
		$size /= 1024;
	}

	return round($size, 2) . $delimiter . $units[$i];
}

//随机6位数字码
function generate_code($length = 6) {
	return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}
//标识选中状态
function array_select($obj, $init) {
	for ($i = 0; $i < count($obj); $i++) {
		if ($obj[$i] == $init) {
			return 'selected';
		}
	}
}
/*
 *标识按条件选中
 *$obj array   数组对象
 *$key  key    要比对的键值
 *$init  obj   要比对的值
 *$selected    新值的比对后的标识
 *return array();
 */
function array_where_select($obj, $key, $init, $selected = 'selected') {
	for ($i = 0; $i < count($obj); $i++) {
		if ($obj[$i][$key] == $init) {
			$obj[$i][$selected] = $selected;
		}
	}
	return $obj;
}
//删除文件及子文件
function deldir($dir) {
	//先删除目录下的文件：
	$dh = opendir($dir);
	while ($file = readdir($dh)) {
		if ($file != "." && $file != "..") {
			$fullpath = $dir . "/" . $file;
			if (!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}

	closedir($dh);
	//删除当前文件夹：
	if (rmdir($dir)) {
		return true;
	} else {
		return false;
	}
}

/*在图片地址前加上绝对地址*/
function Path_Img_Url($array) {
	if ($array = json_decode($array)) {
		foreach ($array as $key => $value) {
			if (is_oss) {
				$arr[] = inage_url($value);
			} else {
				$arr[] = root() . $value;
			}

		}
		return $arr;
	}

}
//检测会员是否登录
function is_login() {
	// return session();
	if (session('users') or session('auth.0')) {
		return true;
	} else {
		return false;
	}
}
/**********
 * 发送邮件 *
$tomail 发送至email地址
$title  标题
$content  内容
 **********/
function sendEmail($tomail, $title, $content) {
	//防止发送乱码
	header("content-type:text/html;charset=utf-8");
	ini_set("magic_quotes_runtime", 0);
	//获取邮件设置信息
	$email_host = C('email_host');
	$email_title = C('email_title'); //发件人名称
	$email_name = C('email_name'); //发件人帐号
	$email_user = C('email_user'); //stmp 帐号
	$email_password = C('email_password'); //stmp  密码
	//实例化PHPMailer类,true表示出现错误时抛出异常
	$mail = new \PHPMailer\PHPMailer();

	// 使用SMTP
	$mail->IsSMTP();

	$mail->CharSet = "UTF-8"; //设定邮件编码
	$mail->Host = $email_host; // SMTP server
	$mail->SMTPDebug = 1; // 启用SMTP调试 1 = errors  2 =  messages
	$mail->SMTPAuth = true; // 服务器需要验证
	$mail->Port = 25; // 设置端口

	$mail->Username = $email_user; //SMTP服务器的用户帐号
	$mail->Password = $email_password; //SMTP服务器的用户密码
	$mail->AddReplyTo($email_name, $email_title); //收件人回复时回复到此邮箱,可以多次执行该方法
	if (is_array($tomail)) {
		foreach ($tomail as $m) {
			$mail->AddAddress($m, 'user');
		}
	} else {
		$mail->AddAddress($tomail, 'user');
	}

	$mail->SetFrom($email_name, $email_title);
	$mail->Subject = $title;

	//以下是邮件内容相关
	$mail->Body = $content;
	$mail->IsHTML(true);

	//$body = file_get_contents('http://ccbbm.sinaapp.com/index.php/ab.html'); //获取html网页内容
	// $mail->MsgHTML(eregi_replace("[]",'',$body));
	if (!$mail->Send()) {
		return false;
	} else {
		return true;
	}
}
/*用户默认头像*/
function user_default() {
	return root() . 'Public/Home/images/default.jpg';
}
/*文档默认图像*/
function doc_default() {
	return root() . 'Public/Images/no-image.jpg';
}

//$msg 错误提示语 抛出错误
function msg_error($msg = 'The model table name can not be empty!') {
	throw new \Exception($msg);
}
/*
 *$type URL 默认生成当前地址URL为二维码
 *$type URL URL存在即使用已存在URL生成二维码
 */
function code($type) {
	if (!$type) {
		return U('Index/code/url/' . str_replace('/', '-', get_url()));
	} else {
		return U('Index/code/url/' . str_replace('/', '-', $type));
	}

}

/**
将查询过的表数据缓存成临时文件
$dbname  tablename  查询的表名称
$array   where      查询条件 array('key'=>value);
 */
function cache_table($dbname, $array) {
	if (!$list = S('cache_' . $dbname)) {
		$list = M($dbname)->field(true)->select();
		S('cache_' . $dbname, $list, array('type' => 'file', 'expire' => C('CACHE_TIME')));
	}
	// 条件是否存在
	if (is_array($array)) {
		return list_search($list, $array);
	} else {
		return $list;
	}

}
/**
将查询过的表数据缓存成临时文件
$dbname  tablename  保底单独一条
 */
function cache_table_find($dbname) {
	if (!$list = S('cache_' . $dbname)) {
		$list = M($dbname)->field(true)->find();
		S('cache_' . $dbname, $list, array('type' => 'file', 'expire' => C('CACHE_TIME')));
	}
	return $list;
}
/*
返回数组第一个
 */
function return_one($array) {
	return $array['0'];
}
/**
替换指定字段
$subject array 要替换的对象
$search  string  要替换的值
$replace string  替换后的值
$is_key  bool    是删除其它字段
 */
function replace_key($subject, $search, $replace, $is_key = true) {
	for ($i = 0; $i < count($subject); $i++) {
		foreach ($subject[$i] as $key => $value) {
			if ($key == $search) {
				if ($is_key) {
					$subject2[$i][str_replace($search, $replace, $key)] = $value;
				} else {
					$subject[$i][str_replace($search, $replace, $key)] = $value;
				}

			}
		}
	}
	if ($is_key) {
		return $subject2;
	} else {
		return $subject;
	}
}
//移动端访问自动切换主题模板
function ismobile() {
	// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
	if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
		return true;
	}

	//此条摘自TPM智能切换模板引擎，适合TPM开发
	if (isset($_SERVER['HTTP_CLIENT']) && 'PhoneClient' == $_SERVER['HTTP_CLIENT']) {
		return true;
	}

	//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
	if (isset($_SERVER['HTTP_VIA']))
	//找不到为flase,否则为true
	{
		return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
	}

	//判断手机发送的客户端标志,兼容性有待提高
	if (isset($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array(
			'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile',
		);
		//从HTTP_USER_AGENT中查找手机浏览器的关键字
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	//协议法，因为有可能不准确，放到最后判断
	if (isset($_SERVER['HTTP_ACCEPT'])) {
		// 如果只支持wml并且不支持html那一定是移动设备
		// 如果支持wml和html但是wml在html之前则是移动设备
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}
//初始化切换模板
function initialize_mobile() {
	//移动设备浏览，则切换模板
	if (C('IS_MOBILE')) {
		if (ismobile()) {
			//设置默认默认主题为 Mobile
			C('DEFAULT_THEME', 'Wap');
		}
	}
}
/**
$text string  要截取的字符串
$leng int     保留的字符串长度
在模版中调用的话，只需要用 {$vo.title|subtext=10} 这样即可，同时实现了，如果没超出长度，则不追加省略号的效果。
 */
function subtxt($txt, $len) {
	return mb_strlen($txt, 'utf8') > $len ? mb_substr($txt, 0, $len, 'utf8') : $txt;
}

function p($p) {
	echo '<pre>';
	print_r($p);
	echo '</pre>';
}
/**
上一页，下一页
$page_type string   prev|next  (上一页|下一页)
 */
function page($page_type) {
	$t = I('get.t', '', 'intval');
	$id = I('get.id', '', 'intval');
	$tpl = return_one(cache_table(GetModelTable(41), array('id' => $t)));

	$Table = M(GetModelTable($tpl['suoshumoxing']));

	switch ($page_type) {
	//上一页
	case 'prev':
		$map['id'] = array('lt', $id);
		$page = $Table->where($map)->order('id desc')->limit('1')->field(true)->find();
		break;
	//下一页
	case 'next':
		$map['id'] = array('gt', $id);
		$page = $Table->where($map)->order('id desc')->limit('1')->field(true)->find();
		break;
	default:
		return false;
		break;
	}

	if ($page) {
		//处理url
		$page['url'] = doc_url($t, $page['id']);
		switch ($page_type) {
		case 'prev':
			$html = "<li><a href=\"{$page['url']}\" title=\"{$page['biaoti']}\"><span aria-hidden='true'>&larr;</span>{$page['biaoti']}</a></li>";
			break;

		case 'next':
			$html = "<li><a href=\"{$page['url']}\" title='{$page['biaoti']}'>{$page['biaoti']}<span aria-hidden='true'>&rarr;</span></a></li>";
			break;
		}

	}

	return $html;
}

function inage_url($image) {
	//return 'http://'.bucket.'.'.hostname.'/'.$image;
	return HOSTNAME . $image;
}

function upload_file_to_alioss($data) {
	$is_oss = is_oss; //是否上传至oss
	if (!$is_oss) {
		return false;

	}
	$access_id = access_id;
	$access_key = access_key;
	$hostname = hostname;
	$bucket = bucket;

	import("Org.Alioss.alioss");
	$oss = new ALIOSS($access_id, $access_key, $hostname, $security_token = NULL);
	//要上传的文件服务器地址
	$file_path = $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . '/' . $data;
	$res = $oss->upload_file_by_file($bucket, $data, $file_path);

	$array = (array) $res;

	switch ($array['status']) {
	case '200':
		return true;
		break;

	default:
		return false;
		break;
	}
}

/**
 * 根据HTML代码获取word文档内容
 * 创建一个本质为mht的文档，该函数会分析文件内容并从远程下载页面中的图片资源
 * 该函数依赖于类MhtFileMaker
 * 该函数会分析img标签，提取src的属性值。但是，src的属性值必须被引号包围，否则不能提取
 *
 * @param string $content HTML内容
 * @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径，那么就需要填写这个参数，来让该函数自动填补成绝对路径。这个参数最后需要以/结束
 * @param bool $isEraseLink 是否去掉HTML内容中的链接
 */
function getWordDocument($content, $absolutePath = "", $isEraseLink = true) {
	import("Org.Util.MhtFileMaker");
	$mht = new MhtFileMaker();
	if ($isEraseLink) {
		$content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i', '$1', $content);
	}
	//去掉链接

	$images = array();
	$files = array();
	$matches = array();
	//这个算法要求src后的属性值必须使用引号括起来
	if (preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i', $content, $matches)) {
		$arrPath = $matches[1];
		for ($i = 0; $i < count($arrPath); $i++) {
			$path = $arrPath[$i];
			$imgPath = trim($path);
			if ($imgPath != "") {
				$files[] = $imgPath;
				if (substr($imgPath, 0, 7) == 'http://') {
					//绝对链接，不加前缀
				} else {
					$imgPath = $absolutePath . $imgPath;
				}
				$images[] = $imgPath;
			}
		}
	}
	$mht->AddContents("tmp.html", $mht->GetMimeType("tmp.html"), $content);

	for ($i = 0; $i < count($images); $i++) {
		$image = $images[$i];
		if (@fopen($image, 'r')) {
			$imgcontent = @file_get_contents($image);
			if ($content) {
				$mht->AddContents($files[$i], $mht->GetMimeType($image), $imgcontent);
			}

		} else {
			echo "file:" . $image . " not exist!<br />";
		}
	}

	return $mht->GetFile();
}
//删除第一个字符串
function romestr($str) {
	return substr($str, 1, strlen($str));
}
function exs($data, $key, $ex = '') {
	return str_replace($key, $ex, $data);
}
//添置按钮
function add_button($array) {
	if (is_array($array)) {
		$html .= "<div class='btn-group pull-right' role='group' aria-label='ddd' style='top: -8px;'>";
		foreach ($array as $key => $value) {
			switch ($value['type']) {
			case 'button':
				$html .= "<button class='btn btn-" . $value['class'] . "' data-toggle='modal' data-target='#" . $value['target'] . "'>" . $value['title'] . "</button>";
				break;
			case 'href':
				$html .= "<button class='btn btn-" . $value['class'] . "' data-toggle='modal' data-target='#" . $value['target'] . "' href=" . $value['url'] . ">" . $value['title'] . "</button>";
				break;
			case 'a':
				$html .= "<a target='_blank' class='btn btn-" . $value['class'] . "' href='" . $value['url'] . "'>" . $value['title'] . "</a>";
				break;
			default:
				$html .= "<a class='btn_ajax btn btn-" . $value['class'] . "' href='" . $value['url'] . "'>" . $value['title'] . "</a>";
				break;
			}

		}
		$html .= "</div>";
		return $html;
	}

}
function unique_arr($array2D, $stkeep = false, $ndformat = true) {
	// 判断是否保留一级数组键 (一级数组键可以为非数字)
	if ($stkeep) {
		$stArr = array_keys($array2D);
	}

	// 判断是否保留二级数组键 (所有二级数组键必须相同)
	if ($ndformat) {
		$ndArr = array_keys(end($array2D));
	}

	//降维,也可以用implode,将一维数组转换为用逗号连接的字符串
	foreach ($array2D as $v) {
		$v = join(",", $v);
		$temp[] = $v;
	}
	//去掉重复的字符串,也就是重复的一维数组
	$temp = array_unique($temp);
	//再将拆开的数组重新组装
	foreach ($temp as $k => $v) {
		if ($stkeep) {
			$k = $stArr[$k];
		}

		if ($ndformat) {
			$tempArr = explode(",", $v);
			foreach ($tempArr as $ndkey => $ndval) {
				$output[$k][$ndArr[$ndkey]] = $ndval;
			}

		} else {
			$output[$k] = explode(",", $v);
		}

	}
	return $output;
}
//通过模型id获取对应表名称
function GetModelTable($number) {
	if (!$number) {
		return false;
	}
	$get = cache_table('model', array('id' => $number));
	return $get['0']['model'];
}
function document_state() {
	$state = C('DOCUMENT_STATE');
	switch ($state) {

	case '0': //不审核
		return $state;
		break;
	case '1': //审核
		return $state;
		break;
	default:
		# code...
		break;
	}
}
//调用插件
function hook($id, $params = array(), $init = false) {
	$h = cache_table(GetModelTable(38), array('id' => $id));
	$shi = $h['0'];
	if ($shi['shifouqiyong'] == '启用') {
		if (!$init) {
			$init = 'index';
		}
		//添插件   $name 插件名
		\Think\Hook::add($init, "Addons\\{$shi['chajianmulu']}\\{$shi['chajianmulu']}Addon");
		//监听一个钩子
		\Think\Hook::listen($init, $params);
	} else {
		// return '插件不存在，或未启用!';
	}

}
/*
@auth  闪电 573525206@qq.com
$number     int          模型id
$array      array        操作html数据
$where      where        查询筛条件
$type       bool         是否显示表格边框
$rollback   string       填写用于回滚处理的函数,默认为flase
return 表格信息
 */
function getTables($number, $array, $where, $type = false, $rollback = '', $limit) {

	$co = I('get.co');
	$to = I('get.to');

	if (!$number) {
		$mid = I('get.mid');
		if ($mid) {
			$number = $mid;
		} else {
			return '模型不存在';
		}

	}
	if ($co && $to) {
		// >=time and <time
		$where['create_time'] = array(array('egt', $co), array('lt', $to), 'and');

	}

	$head = GetModelNan($number);

	//是否回处理滚获取列表信息
	if ($rollback) {
		//回滚处理
		$lists = $rollback(getListInfos($number, $where));
		//插入新增表格头部
		if (is_array($lists['head'])) {
			$head = array_merge($head, $lists['head']);
		}

	} else {
		$lists = getListInfos($number, $where, $limit);
	}

	if ($type) {
		$border = "table-bordered";
	}
	//按字段值查找
	$searchfield = urldecode(I('get.searchfield')); //要查找的值
	if ($searchfield) {
		$field = I('get.field');
		//模糊查询
		$where[$field] = array('like', "%{$searchfield}%");
	}
	$html .= "<div class='table-responsive'>";
	$html .= "<table class='table table-hover {$border}' mid='{$number}'>";
	$html .= "<thead>";
	for ($i = 0; $i < count($head); $i++) {
		$html .= "<th>{$head[$i]['title']}</th>";
	}
	if (!$type) {
		$html .= "<th class='type'>操作</th>";
	}

	$html .= "</thead>";
	// //是否回处理滚获取列表信息
	// if ($rollback) {
	// 	//回滚处理
	// 	$lists = $rollback(getListInfos($number, $where));

	// } else {
	// 	$lists = getListInfos($number, $where);
	// }

	//验证表数据
	$require = getRequire($number);

	//数据不存在提示
	if (!$lists['list']) {
		if (!$type) {
			$spans = count($head) + 1;
		} else {
			$spans = count($head);
		}

		$html .= "<tr>";
		$html .= "<td colspan=" . $spans . "><h2>OO...没有找到相关数据...</h2></td>";
		$html .= "</tr>";
	}

	for ($k = 0; $k < count($lists['list']); $k++) {
		$html .= "<tr>";
		foreach ($lists['list'][$k] as $key => $value) {
			if (!list_search($head, array('field' => $key))) {
				unset($lists['list'][$k][$key]);
			} else {
				//按类型显示数据
				$fildarray = list_search($require, array('field' => $key));
				switch ($fildarray['0']['type']) {
				//关联表模型
				case 'select|char':
					//查出关联表模型对应的数据
					$arrs = explode(',', $fildarray['0']['value']);
					if (!is_array($array)) {
						return false;
					}
					$selectchar = M(GetModelTable($arrs['0']))->where(array('id' => $value))->getField($arrs['1']);
					$html .= "<td>{$selectchar}</td>";
					break;
				//城市
				case 'city|varchar':
					$temps = json_decode($value, true);

					$html .= "<td>" . array_string($temps, '/') . "</td>";
					break;
				//日期
				case 'date|varchar':
					$time = date('Y-m-s H:i', $value);
					$html .= "<td>{$time}</td>";
					break;
				//多选
				case 'checkbox|varchar':

					$html .= "<td>" . array_string(json_decode($value, true), '/') . "</td>";
					break;
				//文件上传
				case 'file|text':
					$default = get_img($value);
					$html .= "<td>";
					for ($i = 0; $i < count($default); $i++) {
						$html .= "<a href='{$default[$i]['src']}' target='_blank'>{$default[$i]['alt']}</a><br/>";
					}
					$html .= "</td>";
					break;
				//联动类型
				case 'link|varchar':
					$default2 = json_decode($value, true);
					$mapwhere['linkid'] = $fildarray['0']['value'];
					$mapwhere['id'] = array('in', array_string($default2));
					$links = M('link')->where($mapwhere)->field('name')->select();
					for ($z = 0; $z < count($links); $z++) {
						$ar[] = $links[$z]['name'];
					}
					$html .= "<td>" . array_string($ar) . "</td>";
					break;
				default:
					$html .= "<td>{$value}</td>";
					break;
				}

			}

		}
		if (!$type) {
			$html .= "<td>";

			if (is_array($array)) {
				$html .= "<div class='btn-group' role='group'>";
				for ($n = 0; $n < count($array); $n++) {
					switch ($array[$n]['type']) {
					case 'delete':
						$html .= "<a class='getajax btn btn-" . $array[$n]['class'] . "' href='" . U($array[$n]['url'], array('id' => $lists['list'][$k]['id'], 'mid' => $number)) . "'>" . $array[$n]['title'] . "</a>";
						break;
					case 'target':
						$html .= "<a target='_blank' class='btn btn-" . $array[$n]['class'] . "' href='" . U($array[$n]['url'], array('id' => $lists['list'][$k]['id'], 'mid' => $number)) . "'>" . $array[$n]['title'] . "</a>";
						break;
					case 'button':
						$html .= "<button class='parentshow btn btn-" . $array[$n]['class'] . "' href='" . U($array[$n]['url'], array('id' => $lists['list'][$k]['id'], 'mid' => $number, 'selected' => $_GET['selected'])) . "' id='{$lists['list'][$k]['id']}' field='{$_GET['field']}'>" . $array[$n]['title'] . "</button>";
						break;
					case 'postU':
						$html .= "<a target='_blank' class='btn btn-" . $array[$n]['class'] . "' href='" . U($array[$n]['url'], array('t' => $array[$n]['columnid'], 'id' => $lists['list'][$k]['id'], 'mid' => $number)) . "'>" . $array[$n]['title'] . "</a>";
						break;
					default:
						$html .= "<a class='btn btn-" . $array[$n]['class'] . "' href='" . U($array[$n]['url'], array('id' => $lists['list'][$k]['id'], 'mid' => $number)) . "'>" . $array[$n]['title'] . "</a>";
						break;
					}

				}
				$html .= "</div>";
			}
			$html .= "</td>";
		}

		$html .= "</tr>";
	}
	$html .= "</table>";
	$html .= "</div>";
	$html .= "<nav>";
	$html .= "<ul class='pagination pull-right'>";
	$html .= $lists['show'];
	$html .= "</ul>";
	$html .= "</nav>";
	return $html;
}
//获取表信息数据 用于bootstrap -table
/*
$number int 模型id
$where where sql查询条件
return 信息数据列表
 */
function getListInfos($number, $where, $limit) {

	if (!$number) {
		return false;
	}
	//查询指定字段
	$field = getmodel($number);
	if ($field) {
		$field = 'id,' . $field . ',create_time';
	} else {
		$field = true;
	}
	$model = M(GetModelTable($number));

	$count = $model->where($where)->count(); // 查询满足要求的总记录数
	if ($limit) {
		$page_count = $limit;
	} else {
		$page_count = C('PAGE_COUNT') ? C('PAGE_COUNT') : 10;
	}

	$Page = new \Think\Page($count, $page_count); // 实例化分页类 传入总记录数和每页显示的记录数(25)
	$show = $Page->show(); // 分页显示输出
	// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
	$list = $model->where($where)->order('id desc')->field($field)->limit($Page->firstRow . ',' . $Page->listRows)->select();
	$data['list'] = $list;
	$data['show'] = $show;
	return $data;
}

//获取表格head导航信息用于bootstrap-table columns
/*
$number int 模型id
return 表头导航信息
 */
function GetModelNan($number, $fields = false) {
	if (!$number) {
		return false;
	}
	//获取模型表名
	$model = GetModelTable($number);
	if (!$model) {
		return false;
	}
	$get = I('get.');
	//查询指定字段
	$field = getmodel($number);
	if ($field) {
		$list = M($model)->field('id,' . $field . ',create_time')->cache(true)->find();
	} else {
		$list = M($model)->cache(true)->find();
	}
	if ($fields) {
		$list = M($model)->cache(true)->find();
	}
	$require = getRequire($number);

	foreach ($list as $key => $value) {
		$n = list_search($require, array('field' => $key));

		if ($n['0']) {
			$find[] = array('field' => $n['0']['field'], 'title' => $n['0']['name'], 'type' => $n['0']['type']);
		} else {
			switch ($key) {
			case 'id':
				$find[] = array('field' => $key, 'title' => 'id');
				break;
			case 'create_time':
				$find[] = array('field' => $key, 'title' => '添加时间');
				break;
				// case 'update_time':
				// 	$find[] = array('field' => $key, 'title' => '更新时间');
				break;
			// case 'uid':
			// 	$find[] = array('field' => $key, 'title' => '用户id');
			// 	break;
			default:
				break;
			}

		}

	}
	return $find;
}
//获取验证表数据
function getRequire($number) {
	if (!$number) {
		return false;
	}
	return cache_table('require', array('modelid' => $number));
	//return M('require')->where(array('modelid' => $number))->order('sort')->cache(true)->select();
}
//获取getmodel
function getmodel($number) {
	if (!$number) {
		return false;
	}
	$info = cache_table('model', array('id' => $number));
	return $info['0']['field'];
	//return M('model')->where(array('id' => $number))->cache(true)->getField('field');
}
function getuserid() {
	return session('auth.id');
}
//栏目导航
function channel() {
	$nav = cache_table('model', array('id' => 44));
	$channel = list_sort_by(cache_table($nav['0']['model']), 'id', 'asc');
	for ($i = 0; $i < count($channel); $i++) {
		$channel[$i]['name'] = $channel[$i]['mingcheng'];
		$channel[$i]['url'] = U("{$channel[$i]['lianjiedizhi']}");
		if ($channel[$i]['shifouxinchuangkoudakai'] = '是') {
			$channel[$i]['_blank'] = '_blank';
		}
	}
	return $channel;
}
//单页
function danye($id) {
	$map['id'] = $id;
	$find = cache_table(GetModelTable(45), $map);
	foreach ($find['0'] as $key => $value) {
		$find['0'][$key] = htmlspecialchars_decode($value);
	}
	return $find['0'];
}
//获取当前栏目下的数据
function get_channel_list($where) {
	$mid = I('get.mid', '', 'intval');
	$id = I('get.id', '', 'intval');
	if (!$mid) {return false;}
	if (!$id) {return false;}

	$info = M(GetModelTable($mid))->where(array('id' => $id))->find();
	//文章所属模型
	$fid = $info['suoshumoxing'];
	$lists = getListInfos($fid, $where);

	//url
	for ($i = 0; $i < count($lists['list']); $i++) {
		$lists['list'][$i]['url'] = doc_url($id, $lists['list'][$i]['id']);
	}

	return $lists;
}
//获取指定栏目下的内容
function get_doc($id, $limit) {
	if (!$id) {
		return false;
	}
	$data = M(GetModelTable(41))->where(array('id' => $id))->find();
	//文章所属模型
	$fid = $data['suoshumoxing'];
	$info = M(GetModelTable($fid))->where($where)->limit($limit)->order('id desc')->select();
	//url
	for ($i = 0; $i < count($info); $i++) {
		$info[$i]['url'] = doc_url($id, $info[$i]['id']);
	}
	return $info;
}
//将图片json转换正常数组
function get_img($data) {
	$default = json_decode($data, true);
	if (is_array($default)) {
		for ($k = 0; $k < count($default['alt']); $k++) {
			//去除开头逗号
			$uploads = romestr($default['path'][$k]);
			unset($list[$i][$field]);
			$list[$k]['src'] = __ROOT__ . $uploads;
			$list[$k]['alt'] = $default['alt'][$k];
		}
		return $list;
	}
}
/**
 *跟据栏目id，获取对应模板
 * $id   int     栏目id
 * $type strong  list列表模板，doc文章模板
 */
function get_tpl($id, $type) {
	$tpl = cache_table(GetModelTable(41), array('id' => $id));
	$t = $tpl['0'];
	switch ($type) {
	case 'list':
		return $tpl['0']['liebiaomoban'];
		break;

	case 'doc':
		return $tpl['0']['neirongmoban'];
		break;
	}
}
//组合文章页url
// $t int 栏目id
//$id int 内容id
function doc_url($t, $id) {
	return U('Index/doc', array('t' => $t, 'id' => $id));
}
